<template>
  <div class="monitor-overview">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <h1 class="text-3xl font-bold text-gray-800 ">
        系统监控概览
      </h1>
      <p class="text-gray-600  mt-2">
        实时监控系统性能指标和运行状态
      </p>
    </div>

    <!-- 数据概览卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
      <!-- 总请求数 -->
      <div class="bg-white  rounded-xl shadow-lg p-6 border-l-4 border-blue-500">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600 ">总请求数</p>
            <p class="text-3xl font-bold text-gray-900 ">
              {{ overviewData.totalRequests || 0 }}
            </p>
          </div>
          <div class="p-3 bg-blue-100  rounded-full">
            <svg class="w-6 h-6 text-blue-600 " fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
            </svg>
          </div>
        </div>
        <div class="mt-4">
          <span class="text-green-600  text-sm font-medium">
            +{{ Math.round((overviewData.totalRequests || 0) * 0.1) }}%
          </span>
          <span class="text-gray-500  text-sm ml-2">较昨日</span>
        </div>
      </div>

      <!-- 成功率 -->
      <div class="bg-white  rounded-xl shadow-lg p-6 border-l-4 border-green-500">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600 ">成功率</p>
            <p class="text-3xl font-bold text-gray-900 ">
              {{ (overviewData.successRate || 0).toFixed(1) }}%
            </p>
          </div>
          <div class="p-3 bg-green-100  rounded-full">
            <svg class="w-6 h-6 text-green-600 " fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
          </div>
        </div>
        <div class="mt-4">
          <div class="w-full bg-gray-200  rounded-full h-2">
            <div 
              class="bg-green-500 h-2 rounded-full transition-all duration-300" 
              :style="{ width: (overviewData.successRate || 0) + '%' }"
            ></div>
          </div>
        </div>
      </div>

      <!-- 平均响应时间 -->
      <div class="bg-white  rounded-xl shadow-lg p-6 border-l-4 border-yellow-500">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600 ">平均响应时间</p>
            <p class="text-3xl font-bold text-gray-900 ">
              {{ overviewData.avgExecutionTime || 0 }}ms
            </p>
          </div>
          <div class="p-3 bg-yellow-100  rounded-full">
            <svg class="w-6 h-6 text-yellow-600 " fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
          </div>
        </div>
        <div class="mt-4">
          <span class="text-yellow-600  text-sm font-medium">
            {{ overviewData.maxExecutionTime || 0 }}ms
          </span>
          <span class="text-gray-500  text-sm ml-2">最大响应时间</span>
        </div>
      </div>

      <!-- 慢查询数量 -->
      <div class="bg-white  rounded-xl shadow-lg p-6 border-l-4 border-red-500">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600 ">慢查询数量</p>
            <p class="text-3xl font-bold text-gray-900 ">
              {{ overviewData.slowQueries || 0 }}
            </p>
          </div>
          <div class="p-3 bg-red-100  rounded-full">
            <svg class="w-6 h-6 text-red-600 " fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.34 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
            </svg>
          </div>
        </div>
        <div class="mt-4">
          <span class="text-red-600  text-sm font-medium">
            {{ overviewData.errorRequests || 0 }}
          </span>
          <span class="text-gray-500  text-sm ml-2">错误请求数</span>
        </div>
      </div>
    </div>

    <!-- 性能趋势图 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
      <!-- 响应时间趋势 -->
      <div class="bg-white  rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800  mb-4">响应时间趋势</h3>
        <div class="h-64">
          <div ref="responseTimeChart" class="w-full h-full"></div>
        </div>
      </div>

      <!-- 请求成功率 -->
      <div class="bg-white  rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800  mb-4">请求成功率</h3>
        <div class="h-64">
          <div ref="successRateChart" class="w-full h-full"></div>
        </div>
      </div>
    </div>

    <!-- 方法执行排名 -->
    <div class="bg-white  rounded-xl shadow-lg p-6 mb-8">
      <div class="flex items-center justify-between mb-4">
        <h3 class="text-lg font-semibold text-gray-800 ">方法执行排名</h3>
        <el-button type="primary" size="small" @click="refreshMethodRanking">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
      <div class="h-80">
        <div ref="methodRankingChart" class="w-full h-full"></div>
      </div>
    </div>

    <!-- 系统状态和实时指标 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
      <!-- 系统状态 -->
      <div class="bg-white  rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800  mb-4">系统状态</h3>
        <div class="space-y-4">
          <div class="flex items-center justify-between p-4 bg-green-50 /20 rounded-lg">
            <div class="flex items-center">
              <div class="w-3 h-3 bg-green-500 rounded-full mr-3 animate-pulse"></div>
              <span class="text-green-700  font-medium">系统运行状态</span>
            </div>
            <span class="text-green-600  font-semibold">正常</span>
          </div>
          <div class="flex items-center justify-between p-4 bg-blue-50 /20 rounded-lg">
            <div class="flex items-center">
              <div class="w-3 h-3 bg-blue-500 rounded-full mr-3"></div>
              <span class="text-blue-700  font-medium">内存使用率</span>
            </div>
            <span class="text-blue-600  font-semibold">{{ systemStatus.memoryUsage || 0 }}%</span>
          </div>
          <div class="flex items-center justify-between p-4 bg-yellow-50 /20 rounded-lg">
            <div class="flex items-center">
              <div class="w-3 h-3 bg-yellow-500 rounded-full mr-3"></div>
              <span class="text-yellow-700  font-medium">CPU使用率</span>
            </div>
            <span class="text-yellow-600  font-semibold">{{ systemStatus.cpuUsage || 0 }}%</span>
          </div>
        </div>
      </div>

      <!-- 实时指标 -->
      <div class="bg-white  rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800  mb-4">实时指标</h3>
        <div class="h-64">
          <div ref="realtimeChart" class="w-full h-full"></div>
        </div>
      </div>
    </div>

    <!-- 最后更新时间 -->
    <div class="mt-6 text-center text-sm text-gray-500 ">
      最后更新时间: {{ overviewData.timestamp || '加载中...' }}
    </div>
  </div>
</template>

<script setup>
import { monitorAPI } from '~/services/api/monitor'
import { Refresh } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

definePageMeta({
  layout: 'admin'
})

// 响应式数据
const overviewData = ref({
  totalRequests: 0,
  successRequests: 0,
  errorRequests: 0,
  successRate: 0,
  avgExecutionTime: 0,
  maxExecutionTime: 0,
  slowQueries: 0,
  timestamp: ''
})

// 系统状态数据
const systemStatus = ref({
  memoryUsage: 0,
  cpuUsage: 0,
  diskUsage: 0,
  status: 'normal'
})

// 图表引用
const responseTimeChart = ref(null)
const successRateChart = ref(null)
const methodRankingChart = ref(null)
const realtimeChart = ref(null)

// 加载状态
const loading = ref(false)

// 获取监控数据
const fetchOverviewData = async () => {
  try {
    loading.value = true
    const result = await monitorAPI.getSystemOverview()
    
    if (result.code === 200 && result.data) {
      overviewData.value = result.data
      // 初始化图表
      nextTick(() => {
        initCharts()
      })
    } else {
      console.error('获取监控数据失败:', result.message)
    }
  } catch (error) {
    console.error('请求监控数据出错:', error)
  } finally {
    loading.value = false
  }
}

// 获取系统状态
const fetchSystemStatus = async () => {
  try {
    const result = await monitorAPI.getSystemStatus()
    if (result.code === 200 && result.data) {
      systemStatus.value = result.data
    }
  } catch (error) {
    console.error('获取系统状态失败:', error)
  }
}

// 获取方法排名
const fetchMethodRanking = async () => {
  try {
    const result = await monitorAPI.getMethodRanking()
    if (result.code === 200 && result.data) {
      updateMethodRankingChart(result.data)
    }
  } catch (error) {
    console.error('获取方法排名失败:', error)
  }
}

// 刷新方法排名
const refreshMethodRanking = () => {
  fetchMethodRanking()
}

// 初始化所有图表
const initCharts = () => {
  initResponseTimeChart()
  initSuccessRateChart()
  initMethodRankingChart()
  initRealtimeChart()
}

// 初始化响应时间趋势图
const initResponseTimeChart = () => {
  if (!responseTimeChart.value) return
  
  const chart = echarts.init(responseTimeChart.value)
  const option = {
    title: {
      text: '响应时间趋势',
      textStyle: {
        color: '#374151',
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a}: {c}ms'
    },
    xAxis: {
      type: 'category',
      data: ['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00'],
      axisLabel: {
        color: '#6b7280'
      }
    },
    yAxis: {
      type: 'value',
      name: '响应时间(ms)',
      axisLabel: {
        color: '#6b7280'
      }
    },
    series: [{
      name: '平均响应时间',
      type: 'line',
      smooth: true,
      data: [overviewData.value.avgExecutionTime || 0, 45, 52, 38, 65, 72, 58, 63, 48, 55, 42, 49],
      itemStyle: {
        color: '#3b82f6'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(59, 130, 246, 0.3)'
          }, {
            offset: 1, color: 'rgba(59, 130, 246, 0.1)'
          }]
        }
      }
    }]
  }
  chart.setOption(option)
  
  // 响应式
  window.addEventListener('resize', () => chart.resize())
}

// 初始化成功率图
const initSuccessRateChart = () => {
  if (!successRateChart.value) return
  
  const chart = echarts.init(successRateChart.value)
  const option = {
    title: {
      text: '请求成功率',
      textStyle: {
        color: '#374151',
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}%'
    },
    series: [{
      name: '成功率',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['50%', '60%'],
      data: [
        { value: overviewData.value.successRate || 0, name: '成功', itemStyle: { color: '#10b981' } },
        { value: 100 - (overviewData.value.successRate || 0), name: '失败', itemStyle: { color: '#ef4444' } }
      ],
      label: {
        show: true,
        formatter: '{b}: {c}%',
        color: '#374151'
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  chart.setOption(option)
  
  // 响应式
  window.addEventListener('resize', () => chart.resize())
}

// 初始化方法排名图
const initMethodRankingChart = () => {
  if (!methodRankingChart.value) return
  
  const chart = echarts.init(methodRankingChart.value)
  const option = {
    title: {
      text: '方法执行排名',
      textStyle: {
        color: '#374151',
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        color: '#6b7280'
      }
    },
    yAxis: {
      type: 'category',
      data: ['方法A', '方法B', '方法C', '方法D', '方法E'],
      axisLabel: {
        color: '#374151'
      }
    },
    series: [{
      name: '执行时间',
      type: 'bar',
      data: [120, 98, 85, 72, 65],
      itemStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 1, y2: 0,
          colorStops: [{
            offset: 0, color: '#3b82f6'
          }, {
            offset: 1, color: '#1d4ed8'
          }]
        }
      }
    }]
  }
  chart.setOption(option)
  
  // 响应式
  window.addEventListener('resize', () => chart.resize())
}

// 更新方法排名图表
const updateMethodRankingChart = (data) => {
  if (!methodRankingChart.value) return
  
  const chart = echarts.getInstanceByDom(methodRankingChart.value)
  if (chart) {
    const option = chart.getOption()
    option.yAxis.data = data.map(item => item.methodName || item.name)
    option.series[0].data = data.map(item => item.executionTime || item.time)
    chart.setOption(option)
  }
}

// 初始化实时指标图
const initRealtimeChart = () => {
  if (!realtimeChart.value) return
  
  const chart = echarts.init(realtimeChart.value)
  const option = {
    title: {
      text: '实时指标',
      textStyle: {
        color: '#374151',
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['请求数', '响应时间'],
      textStyle: {
        color: '#374151'
      }
    },
    xAxis: {
      type: 'category',
      data: ['1分钟前', '50秒前', '40秒前', '30秒前', '20秒前', '10秒前', '现在'],
      axisLabel: {
        color: '#6b7280'
      }
    },
    yAxis: [{
      type: 'value',
      name: '请求数',
      axisLabel: {
        color: '#6b7280'
      }
    }, {
      type: 'value',
      name: '响应时间(ms)',
      axisLabel: {
        color: '#6b7280'
      }
    }],
    series: [{
      name: '请求数',
      type: 'line',
      yAxisIndex: 0,
      data: [65, 72, 68, 75, 82, 78, 85],
      itemStyle: {
        color: '#10b981'
      }
    }, {
      name: '响应时间',
      type: 'line',
      yAxisIndex: 1,
      data: [45, 52, 48, 55, 62, 58, 65],
      itemStyle: {
        color: '#f59e0b'
      }
    }]
  }
  chart.setOption(option)
  
  // 响应式
  window.addEventListener('resize', () => chart.resize())
}

// 页面加载时获取数据
onMounted(() => {
  fetchOverviewData()
  fetchSystemStatus()
  fetchMethodRanking()
})

// 定时刷新数据（每60秒）
let refreshTimer = null
onMounted(() => {
  refreshTimer = setInterval(() => {
    fetchOverviewData()
    fetchSystemStatus()
  }, 60000)
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
.monitor-overview {
  @apply min-h-screen bg-gray-50 ;
}

.page-header {
  @apply bg-white  rounded-xl shadow-lg p-6;
}

/* 卡片悬停效果 */
.grid > div:hover {
  @apply transform transition-all duration-200;
  transform: translateY(-2px);
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

/* 进度条动画 */
.bg-green-500 {
  transition: width 0.5s ease-in-out;
}

/* 状态指示器动画 */
.animate-pulse {
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: .5;
  }
}
</style>
